import React, {PureComponent} from "react"
import QRCode from 'qrcode.react';
import {actionCreators} from "../main/store";
import {connect} from "react-redux";
import {Form, Input, Button, Select, message, Table} from 'antd';

const {Option} = Select;

class QrCodeFormComponent extends PureComponent {

    state = {
        devices: [],
        columns: [
            {
                title: '设备名称',
                dataIndex: 'device',
            }, {
                title: '设备状态',
                dataIndex: 'status',
                render: text => {
                    return <span style={{color: (text === 'device') ? null : 'red'}}>{text}</span>;
                },
            }, {
                title: 'model',
                dataIndex: 'model',
            }, {
                title: 'serialno',
                dataIndex: 'serialno',
            }, {
                title: 'product',
                dataIndex: 'product',
            }, {
                title: 'release',
                dataIndex: 'release',
            }, {
                title: 'sdk',
                dataIndex: 'sdk',
            }, {
                title: 'brand',
                dataIndex: 'brand',
            },
        ],
    };

    componentDidMount() {
        this.props.loadAPPServiceHost();
        this.props.loadRegWifiDevicesPost(devices => {
            this.setState({devices})
        });
    }

    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, fieldsValue) => {
            if (err) {
                return;
            }
            const client_ip = fieldsValue['client_ip'];
            const serial = fieldsValue['serial'];
            let json = {
                client: client_ip,
                serial: serial
            };
            this.props.loadRegWifiDevicesGet(json, msg => {
                message.success(`注册成功：${msg}`);
                setTimeout(() => {
                    this.props.loadRegWifiDevicesPost(devices => {
                        this.setState({devices})
                    });
                }, 2000);
            });
        });
    };

    restartADB = () => {
        this.props.loadReStartADB(msg => {
            message.success(msg);
            setTimeout(() => {
                this.props.loadRegWifiDevicesPost(devices => {
                    this.setState({devices})
                });
            }, 2000);
        })
    };

    render() {
        const {serviceHost} = this.props;
        const {getFieldDecorator} = this.props.form;
        const {devices, columns} = this.state;
        let w = 40;
        return (
            <div>
                <p style={{
                    float: 'left',
                    width: '100%',
                    lineHeight: 2,
                    marginTop: '20px',
                    marginLeft: '20px'
                }}>APP扫码注册不了，手动输入注册。</p>
                <p style={{
                    float: 'left',
                    width: '100%',
                    lineHeight: 2,
                    marginLeft: '20px'
                }}>PS:设备需要连接电脑，注册成功后可以拔掉设备。</p>

                <Form layout={'inline'} style={{marginLeft: '20px', paddingTop: '84px'}} onSubmit={this.handleSubmit}>
                    <Form.Item label="client_ip">
                        {getFieldDecorator('client_ip', {
                            rules: [{required: true, message: '请输入设备ip'}],
                        })(
                            <Input placeholder="请输入设备ip"/>,
                        )}
                    </Form.Item>
                    <Form.Item label="serial">
                        {getFieldDecorator('serial', {
                            initialValue: "选择设备",
                            rules: [{required: true, message: '请选择设备'}],
                        })(
                            //onChange={handleChange}
                            <Select style={{width: 200}}>
                                {devices.map((value, index, arr) => {
                                    return (<Option key={index} value={value.device}>{value.device}</Option>);
                                })}
                            </Select>,
                        )}
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            注册设备
                        </Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={this.restartADB}>
                            重启ADB
                        </Button>
                    </Form.Item>
                </Form>

                <Table
                    style={{padding: '20px'}}
                    columns={columns}
                    dataSource={devices}
                    rowKey={record => record.device}
                    bordered
                    title={() => '设备列表'}
                    // footer={() => 'Footer'}
                />
                <div className={'qrcode-content'}>
                    <div className={'qrcode-content-item'}>
                        <p style={{
                            float: 'left',
                            textAlign: 'center',
                            width: '100%',
                            marginBottom: '20px'
                        }}>扫码下载APK</p>
                        <QRCode
                            className={'qrcode-content-item-qrcode'}
                            size={window.document.body.scrollWidth}
                            style={{width: w + '%', height: w + '%'}}
                            level={"H"}
                            bgColor={"transparent"} fgColor={"#1890ff"}
                            value={serviceHost + 'getwifiip.apk'}/>
                    </div>
                    <div className={'qrcode-content-item'}>
                        <p style={{
                            float: 'left',
                            textAlign: 'center',
                            width: '100%',
                            marginBottom: '20px'
                        }}>APP扫码注册WIFI设备</p>
                        <QRCode
                            className={'qrcode-content-item-qrcode'}
                            size={window.document.body.scrollWidth}
                            style={{width: w + '%', height: w + '%'}}
                            level={"H"}
                            bgColor={"transparent"} fgColor={"#1890ff"}
                            value={serviceHost + 'api/reg_wifi_devices'}/>
                    </div>
                </div>
            </div>
        )
    }
}

const mapState = (state) => ({
    serviceHost: state.getIn(['home', 'serviceHost']),
});

const mapDispatch = (dispatch) => ({
    loadAPPServiceHost() {
        dispatch(actionCreators.loadAPPServiceHost())
    },
    loadRegWifiDevicesPost(func) {
        dispatch(actionCreators.loadRegWifiDevicesPost(func))
    },
    loadRegWifiDevicesGet(json, func) {
        dispatch(actionCreators.loadRegWifiDevicesGet(json, func))
    },
    loadReStartADB(func) {
        dispatch(actionCreators.loadReStartADB(func))
    },
});

const QrCodeComponent = Form.create()(QrCodeFormComponent);
export default connect(mapState, mapDispatch)(QrCodeComponent);
